package org.framework.common.ext.util.datasource;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URLDecoder;

import org.apache.commons.io.IOUtils;
import org.framework.common.ext.util.PropertiesUtil;
import org.framework.common.ext.util.StringUtil;

/**
 * 动态数据源配置文件工具类
 * <p>描述: </p>
 * <p>Company: Professional</p>
 * @author chanlong(陈龙)
 * @date 2016年1月13日 上午10:43:28
 * @version 1.0.2016
 */
public class DynamicDataSourceConfig {

	private static String CONFIG_FILE_PATH = "/config/datasource/config.properties";
	private static String CONFIG_KEY_TEMPLATE = "cfg.template";
	private static String CONFIG_KEY_STORAGE = "cfg.storage";
	private static String CONFIG_KEY_TEMPURL = "cfg.tempurl";
	private static String DEFAULT_DB_URL = "localhost";
	private static String DEFAULT_DB_NAME = "{dbname}";

	private static String templpath = null;
	private static String storage = null;
	private static String tempurl = null;
	
	static{
		PropertiesUtil config = PropertiesUtil.loader(CONFIG_FILE_PATH);
		templpath = config.getProperty(CONFIG_KEY_TEMPLATE);
		storage = config.getProperty(CONFIG_KEY_STORAGE);
		tempurl = config.getProperty(CONFIG_KEY_TEMPURL);
	}
	
	/**
	 * 创建动态数据源配置文件.
	 * @param dsname
	 * @author chanlong(陈龙)
	 * @date 2016年1月13日 下午2:57:20
	 */
	public static void create(final String dbname, final String dburl){
		String url = tempurl.replace(DEFAULT_DB_NAME, dbname);
		
		if(StringUtil.isNotEmpty(dburl)) {
			url = url.replace(DEFAULT_DB_URL, dburl);
		}
		
		create(dbname, url, null, null);
	}
	
	/**
	 * 创建动态数据源配置文件.
	 * @param dsname
	 * @author chanlong(陈龙)
	 * @date 2016年1月13日 下午2:53:04
	 */
	public static void create(final String dbname, final String dburl, final String user, final String password){
		// 替换配置文件中的各项属性
		String cfg = readerTemplate().replace("$DATASOURCE_NAME", dbname).replace("$URL", dburl);
		if(StringUtil.isNotEmpty(user)){
			cfg = cfg.replace("$USER", user);
		}
		if(StringUtil.isNotEmpty(password)){
			cfg = cfg.replace("$PASSWORD", password);
		}
		
		// 输出配置文件
		FileOutputStream output = null;
		OutputStreamWriter writer = null; 
		try {
			String path = DynamicDataSourceConfig.class.getClassLoader().getResource("/").getPath();
			String filepath = new StringBuilder(URLDecoder.decode(path,"utf-8")).append(storage).append("/").append(dbname).append(".xml").toString();
			output = new FileOutputStream(filepath);
			writer = new OutputStreamWriter(output, "utf-8");
			IOUtils.write(cfg, output);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
			IOUtils.closeQuietly(output);
			IOUtils.closeQuietly(writer);
		}
	}
	
	/**
	 * 读取动态数据源配置模版.
	 * @return
	 * @author chanlong(陈龙)
	 * @date 2016年1月13日 下午2:52:26
	 */
	private static String readerTemplate() {
		InputStream input = null;
		InputStreamReader reader = null;
		BufferedReader buffered = null;
		StringBuffer content = new StringBuffer();
		try{
			input = DynamicDataSourceConfig.class.getClassLoader().getResourceAsStream(templpath);
			reader = new InputStreamReader(input, "UTF-8");
			buffered = new BufferedReader(reader);
			String line = null;
			String separator = System.getProperty("line.separator");
			while ((line = buffered.readLine()) != null) {
				content.append(line).append(separator);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			IOUtils.closeQuietly(input);
			IOUtils.closeQuietly(reader);
			IOUtils.closeQuietly(buffered);
		}
		return content.toString();
	}
	
	public static void main(String[] args) {
		System.out.println(readerTemplate());
		create("miwawa_haya", "jdbc:mysql://localhost:3306/miwawa_haya?useUnicode=true&amp;characterEncoding=utf8");
	}
}
